from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api import deps
from app.models.user import User
from app.schemas.notification import NotificationCreate, NotificationUpdate, NotificationResponse
from app.services import notification as notification_service


router = APIRouter()


@router.get("/", response_model=List[NotificationResponse])
async def read_notifications(
    db: AsyncSession = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    is_read: Optional[bool] = None,
    notification_type: Optional[str] = None,
    priority: Optional[str] = None,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取当前用户的通知列表，可按已读状态、类型和优先级筛选"""
    notifications = await notification_service.get_notifications_by_recipient(
        db=db, recipient_id=current_user.id, skip=skip, limit=limit,
        is_read=is_read, notification_type=notification_type, priority=priority
    )
    return notifications


@router.post("/", response_model=NotificationResponse, status_code=status.HTTP_201_CREATED)
async def create_notification(
    *,
    db: AsyncSession = Depends(deps.get_db),
    notification_in: NotificationCreate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """创建通知"""
    # 检查权限：只有超级用户或项目管理员可以创建系统通知
    if notification_in.notification_type == "system" and not (current_user.is_superuser or current_user.is_project_manager):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions to create system notifications",
        )
    notification = await notification_service.create_notification(
        db=db, obj_in=notification_in, sender_id=current_user.id
    )
    return notification


@router.get("/{notification_id}", response_model=NotificationResponse)
async def read_notification(
    *,
    db: AsyncSession = Depends(deps.get_db),
    notification_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取特定通知详情"""
    notification = await notification_service.get_notification_by_id(db=db, id=notification_id)
    if not notification:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Notification not found",
        )
    # 检查权限：只有通知的接收者、发送者或超级用户可以查看通知
    if (notification.recipient_id != current_user.id 
            and notification.sender_id != current_user.id 
            and not current_user.is_superuser):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    return notification


@router.put("/{notification_id}", response_model=NotificationResponse)
async def update_notification(
    *,
    db: AsyncSession = Depends(deps.get_db),
    notification_id: int,
    notification_in: NotificationUpdate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """更新通知"""
    notification = await notification_service.get_notification_by_id(db=db, id=notification_id)
    if not notification:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Notification not found",
        )
    # 检查权限：只有通知的发送者或超级用户可以更新通知
    if notification.sender_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    notification = await notification_service.update_notification(
        db=db, db_obj=notification, obj_in=notification_in
    )
    return notification


@router.delete("/{notification_id}", response_model=NotificationResponse)
async def delete_notification(
    *,
    db: AsyncSession = Depends(deps.get_db),
    notification_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """删除通知"""
    notification = await notification_service.get_notification_by_id(db=db, id=notification_id)
    if not notification:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Notification not found",
        )
    # 检查权限：只有通知的接收者、发送者或超级用户可以删除通知
    if (notification.recipient_id != current_user.id 
            and notification.sender_id != current_user.id 
            and not current_user.is_superuser):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    notification = await notification_service.delete_notification(db=db, id=notification_id)
    return notification


@router.put("/{notification_id}/read", response_model=NotificationResponse)
async def mark_notification_as_read(
    *,
    db: AsyncSession = Depends(deps.get_db),
    notification_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """将通知标记为已读"""
    notification = await notification_service.get_notification_by_id(db=db, id=notification_id)
    if not notification:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Notification not found",
        )
    # 检查权限：只有通知的接收者可以将通知标记为已读
    if notification.recipient_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    notification = await notification_service.mark_notification_as_read(db=db, id=notification_id)
    return notification


@router.put("/mark-all-as-read", response_model=dict)
async def mark_all_notifications_as_read(
    *,
    db: AsyncSession = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """将当前用户的所有通知标记为已读"""
    count = await notification_service.mark_all_notifications_as_read(
        db=db, recipient_id=current_user.id
    )
    return {"message": f"Marked {count} notifications as read"}